package com.narbeshuber.tablet.lasalara.http;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

import com.narbeshuber.tablet.lasalara.LasaLaraActivity;
import com.narbeshuber.tablet.lasalara.fragment.BookFragment;
import com.narbeshuber.tablet.lasalara.model.Book;

public class AddBookTask extends AsyncTask<String, Object, String> {
	
	LasaLaraActivity lasalaraActivity;
	ProgressDialog dialog;
	String bookName;
	String bookAuthor;
	
	public AddBookTask(LasaLaraActivity lasalaraActivity) {
		this.lasalaraActivity = lasalaraActivity;
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		dialog = ProgressDialog.show(lasalaraActivity, "",
				"Adding book. Please wait...", true);
	}

	@Override
	protected String doInBackground(String... params) {
		
		try {
			
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(
					"http://1.narbeshuber.appspot.com/addbook");

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("em", params[0].toLowerCase()));
			nameValuePairs.add(new BasicNameValuePair("bt", params[1].toLowerCase()));
			nameValuePairs.add(new BasicNameValuePair("uk", params[2]));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);

			InputStream is = response.getEntity().getContent();
			BufferedInputStream bis = new BufferedInputStream(is, 700);
			ByteArrayBuffer baf = new ByteArrayBuffer(20);
			int current = 0;

			while ((current = bis.read()) != -1) {
				baf.append((byte) current);
			}

			final String retval = new String(baf.toByteArray());
			JSONObject jsonBook = new JSONObject(retval);
			
			if (jsonBook.has("err")) {
				String errText = "";
				if (jsonBook.getString("err").equals("0")) {
					errText = "The email address was not found.";
				} else if (jsonBook.getString("err").equals("1")) {
					errText = "A book title by that author was not found.";
				} else if (jsonBook.getString("err").equals("2")) {
					errText = "This book is already in your library.";
				}

				return errText;
			}
			
			Book book = new Book();
			book.setKey(jsonBook.getString("bk"));
			book.setAuthorName(jsonBook.getString("name"));
			book.setAuthorEmail(jsonBook.getString("email"));
			book.setTitle(jsonBook.getString("title"));
			book.setDr(jsonBook.getString("dr"));
			book.setInstitution(jsonBook.getString("institution"));
			lasalaraActivity.getDbHelper().beginTransaction();
			lasalaraActivity.getDbHelper().insertBook(book);
			lasalaraActivity.getDbHelper().endTransaction();

		} catch (Exception e) {
			Log.d("Exception: ", e.getMessage());
		}
		return null;
	}
	
	protected void onPostExecute(String errText) {
		dialog.dismiss();
		
		lasalaraActivity.getDbHelper().beginTransaction();
		List<Book> books = lasalaraActivity.getDbHelper().getAllBooks();
		lasalaraActivity.getDbHelper().endTransaction();
		
		BookFragment.getInstance().getListAdapter().setBooks(books);
		BookFragment.getInstance().getListAdapter().refreshList();
		
		if (errText != null) {
			new AlertDialog.Builder(lasalaraActivity)
			.setTitle("Error adding book.")
			.setMessage(errText)
			.setPositiveButton("OK", null).show();
		}
	}

}
